import { Component } from 'react';
import './App.css';
import { Add, Footer, List } from './components';

export default class App extends Component {
    state = {
        todos: [
            { id: '001', title: '抽烟', completed: true },
            { id: '002', title: '喝酒', completed: false },
            { id: '003', title: '烫头', completed: true }
        ]
    };

    // 删除待办项
    removeTodoItem = id => {
        const newTodos = this.state.todos.filter(item => item.id !== id);
        this.setState({
            todos: newTodos
        });
    };

    // 处理单个待办项状态确认框变化
    checkBoxChanged = (id, newCheckedValue) => {
        const newTodos = this.state.todos.map(item => {
            if (item.id === id) {
                item.completed = newCheckedValue;
            }
            return item;
        });

        this.setState({
            todos: newTodos
        });
    };

    // 传给 Add 组件的函数，用于接收子组件传来的数据
    eventBus = newToDoItem => {
        this.setState({
            todos: [newToDoItem, ...this.state.todos]
        });
    };

    // 传给 Footer 组件的函数，用于接收子组件传来的数据
    allCheckedChanged = AllCheckedStatus => {
        this.setState({
            todos: this.state.todos.map(todo => ({
                ...todo,
                completed: AllCheckedStatus.target.checked
            }))
        });
    };

    handleRemoveCompleted = () => {
        const pemdingCompletedTodo = this.state.todos.filter(todo => !todo.completed);
        this.setState({
            todos: pemdingCompletedTodo
        });
    };

    render() {
        return (
            <div className="todo-container">
                <div className="todo-wrap">
                    {/* 将函数对象传递给子组件，子组件调用该函数并将数据传入，从而实现子组件向父组件传递数据的功能 */}
                    <Add eventBus={this.eventBus} />
                    <List
                        {...this.state}
                        removeTodoItem={this.removeTodoItem}
                        checkBoxChanged={this.checkBoxChanged}
                    />
                    <Footer
                        {...this.state}
                        allCheckedChanged={this.allCheckedChanged}
                        handleRemoveCompleted={this.handleRemoveCompleted}
                    />
                </div>
            </div>
        );
    }
}
